/**
 * 用户状态模块
 * @author 王勇程 <laughskydragon@qq.com>
 */

const state = {
  isLogin: false,           // 登录状态
  userToken: '',            // 用户令牌
  userInfo: {},             // 用户信息
  followList: [],           // 关注列表
  tokenExpireTime: 0,       // token过期时间
  loginRetryCount: 0        // 登录重试次数
}

const mutations = {
  SET_LOGIN_STATUS(state, status) {
    state.isLogin = status
  },
  SET_USER_TOKEN(state, token) {
    state.userToken = token
    // 同步到本地存储
    if (token) {
      uni.setStorageSync('user_token', token)
      // 设置token过期时间（7天）
      const expireTime = Date.now() + 7 * 24 * 60 * 60 * 1000
      state.tokenExpireTime = expireTime
      uni.setStorageSync('token_expire_time', expireTime)
      // 重置重试次数
      state.loginRetryCount = 0
    } else {
      uni.removeStorageSync('user_token')
      uni.removeStorageSync('token_expire_time')
      state.tokenExpireTime = 0
    }
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    // 同步到本地存储
    if (userInfo && Object.keys(userInfo).length > 0) {
      uni.setStorageSync('user_info', userInfo)
    } else {
      uni.removeStorageSync('user_info')
    }
  },
  UPDATE_FOLLOW_LIST(state, followList) {
    state.followList = followList
  },
  SET_TOKEN_EXPIRE_TIME(state, expireTime) {
    state.tokenExpireTime = expireTime
  },
  INCREMENT_LOGIN_RETRY(state) {
    state.loginRetryCount++
  },
  RESET_LOGIN_RETRY(state) {
    state.loginRetryCount = 0
  }
}

const actions = {
  // 登录操作
  login({ commit }, { userToken, userInfo }) {
    try {
      commit('SET_USER_TOKEN', userToken)
      commit('SET_USER_INFO', userInfo)
      commit('SET_LOGIN_STATUS', true)
      commit('RESET_LOGIN_RETRY')
      
      console.log('用户登录成功，状态已更新')
      return Promise.resolve()
    } catch (error) {
      console.error('登录状态更新失败:', error)
      return Promise.reject(error)
    }
  },
  
  // 退出登录
  logout({ commit }) {
    try {
      commit('SET_USER_TOKEN', '')
      commit('SET_USER_INFO', {})
      commit('SET_LOGIN_STATUS', false)
      commit('UPDATE_FOLLOW_LIST', [])
      commit('SET_TOKEN_EXPIRE_TIME', 0)
      commit('RESET_LOGIN_RETRY')
      
      console.log('用户已退出登录')
      return Promise.resolve()
    } catch (error) {
      console.error('退出登录失败:', error)
      return Promise.reject(error)
    }
  },
  
  // 检查登录状态
  checkLoginStatus({ commit, state, rootGetters }) {
    try {
      // 如果开启了登录跳过，直接返回已登录状态
      if (rootGetters['app/skipLogin']) {
        commit('SET_LOGIN_STATUS', true)
        // 设置模拟用户信息
        commit('SET_USER_INFO', {
          id: 1,
          nickname: '测试用户',
          avatar: '',
          phone: '',
          vip_level: 1
        })
        return true
      }
      
      const userToken = uni.getStorageSync('user_token')
      const userInfo = uni.getStorageSync('user_info')
      const tokenExpireTime = uni.getStorageSync('token_expire_time')
      
      // 检查token是否过期
      if (tokenExpireTime && Date.now() > tokenExpireTime) {
        console.log('Token已过期，清除登录状态')
        // token已过期，清除登录状态
        commit('SET_USER_TOKEN', '')
        commit('SET_USER_INFO', {})
        commit('SET_LOGIN_STATUS', false)
        commit('SET_TOKEN_EXPIRE_TIME', 0)
        return false
      }
      
      if (userToken && userInfo) {
        commit('SET_USER_TOKEN', userToken)
        commit('SET_USER_INFO', userInfo)
        commit('SET_TOKEN_EXPIRE_TIME', tokenExpireTime || 0)
        commit('SET_LOGIN_STATUS', true)
        return true
      } else {
        commit('SET_LOGIN_STATUS', false)
        return false
      }
    } catch (error) {
      console.error('检查登录状态失败:', error)
      commit('SET_LOGIN_STATUS', false)
      return false
    }
  },
  
  // 更新用户信息
  updateUserInfo({ commit }, userInfo) {
    try {
      commit('SET_USER_INFO', userInfo)
      console.log('用户信息已更新')
      return Promise.resolve()
    } catch (error) {
      console.error('更新用户信息失败:', error)
      return Promise.reject(error)
    }
  },
  
  // 刷新token
  refreshToken({ commit, state }) {
    try {
      // 延长token过期时间
      const expireTime = Date.now() + 7 * 24 * 60 * 60 * 1000
      commit('SET_TOKEN_EXPIRE_TIME', expireTime)
      uni.setStorageSync('token_expire_time', expireTime)
      console.log('Token已刷新')
      return Promise.resolve()
    } catch (error) {
      console.error('刷新Token失败:', error)
      return Promise.reject(error)
    }
  },
  
  // 处理token错误
  handleTokenError({ commit, state, dispatch }) {
    try {
      commit('INCREMENT_LOGIN_RETRY')
      
      // 如果重试次数超过3次，强制退出登录
      if (state.loginRetryCount > 3) {
        console.log('Token错误重试次数过多，强制退出登录')
        dispatch('logout')
        
        // 跳转到登录页
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/index/index'
          })
        }, 1000)
        
        return Promise.resolve()
      }
      
      // 清除当前token但保留用户信息，允许重新登录
      commit('SET_USER_TOKEN', '')
      commit('SET_LOGIN_STATUS', false)
      
      console.log(`Token错误，第${state.loginRetryCount}次重试`)
      return Promise.resolve()
    } catch (error) {
      console.error('处理Token错误失败:', error)
      return Promise.reject(error)
    }
  },
  
  // 自动登录检查
  async autoLoginCheck({ dispatch, getters }) {
    try {
      const isLogin = dispatch('checkLoginStatus')
      
      if (isLogin && !getters.isTokenExpired) {
        // 如果已登录且token未过期，刷新token
        await dispatch('refreshToken')
        return true
      } else if (getters.isTokenExpired) {
        // 如果token过期，处理token错误
        await dispatch('handleTokenError')
        return false
      }
      
      return false
    } catch (error) {
      console.error('自动登录检查失败:', error)
      return false
    }
  }
}

const getters = {
  isLogin: state => state.isLogin,
  userToken: state => state.userToken,
  userInfo: state => state.userInfo,
  followList: state => state.followList,
  isVip: state => state.userInfo.vip_level > 0,
  tokenExpireTime: state => state.tokenExpireTime,
  isTokenExpired: state => state.tokenExpireTime > 0 && Date.now() > state.tokenExpireTime,
  loginRetryCount: state => state.loginRetryCount,
  // 获取用户昵称，优先显示nickname，其次显示phone的部分
  userNickname: state => {
    if (state.userInfo.nickname) {
      return state.userInfo.nickname
    }
    if (state.userInfo.phone) {
      return state.userInfo.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    }
    return '微信用户'
  },
  // 获取用户头像，有默认头像
  userAvatar: state => {
    return state.userInfo.avatar || '/static/images/default-avatar.png'
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}